#!/usr/bin/env python
# -*- coding: utf-8 -*-


def path_parse(path_info, str_def, str_err):
    '解析path_info，把诸如"ab/cd/"分离出ab和cd出来'
    '字符串必须符合"aa/bb/cc/dd/"形式，可以有多个'
    str1 = path_info[:path_info.find('/')]
    if str1 == '':
        return str_def, str_def, ''
    if not str1.isalnum():
        return str_err, str_def, ''

    path_info = path_info[path_info.find('/') + 1:]
    str2 = path_info[:path_info.find('/')]
    if str2 == '':
        return str1, str_def, ''
    if not str2.isalnum():
        return str_err, str_def, ''

    str3 = path_info[path_info.find('/') + 1:]
    return str1, str2, str3


def application(environ, start_response):
    import os
    import sys

    cur_path = os.path.dirname(os.path.abspath(__file__))
    sys.path.append(cur_path)
    from util import config

    # 从PATH_INFO确定需要调用的handle和action
    path_info = environ["PATH_INFO"].strip('/') + '/'
    handle_name, action_name, rest_path = path_parse(
            path_info,
            config.CONFIG['handle_default'],
            config.CONFIG['handle_error'])

    handle_name = 'Handle' + handle_name.capitalize()
    dir_handle = config.CONFIG['dir_handle']
    handle_path = config.CONFIG['root_path'] + dir_handle
    if not os.path.isfile('%s/%s.py' % (handle_path, handle_name)):
        handle_name = config.CONFIG['handle_error']
        handle_name = 'Handle' + handle_name.capitalize()

    # 加载handle类
    exec_str = 'from %s.%s import %s as HandleMod'
    exec(exec_str % (dir_handle, handle_name, handle_name))

    handle_mod = HandleMod(environ)
    if handle_mod.is_action(action_name):
        exec('handle_mod.action_%s()' % action_name)
    else:
        action_name = config.CONFIG['handle_default']
        handle_mod.action_index()
    outstr = handle_mod.render(action_name)

    response_status = handle_mod.get_response_status()
    response_header = handle_mod.get_header()
    start_response(response_status, response_header)
    return [outstr.encode('utf-8')]
